package com.maker.LMMS.service;

/**
 * @author : zimu
 * @Date: 2018/8/8 19:27
 * @description :
 */

import com.blade.mvc.http.Response;
import jetbrick.util.FilenameUtils;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

public class FileOperation {
    /*
     * 根据尺寸图片居中裁剪
     */
    public  void cutCenterImage(String src,String dest,int w,int h,String type) throws IOException{
        Iterator iterator = ImageIO.getImageReadersByFormatName(type);
        ImageReader reader = (ImageReader)iterator.next();
        InputStream in=new FileInputStream(src);
        ImageInputStream iis = ImageIO.createImageInputStream(in);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int imageIndex = 0;
        Rectangle rect = new Rectangle((reader.getWidth(imageIndex)-w)/2, (reader.getHeight(imageIndex)-h)/2, w, h);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0,param);
        ImageIO.write(bi, type, new File(dest));

    }
    /*
     * 图片裁剪二分之一
     */
    public  void cutHalfImage(String src,String dest,String type) throws IOException{
        Iterator iterator = ImageIO.getImageReadersByFormatName(type);
        ImageReader reader = (ImageReader)iterator.next();
        InputStream in=new FileInputStream(src);
        ImageInputStream iis = ImageIO.createImageInputStream(in);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int imageIndex = 0;
        int width = reader.getWidth(imageIndex)/2;
        int height = reader.getHeight(imageIndex)/2;
        Rectangle rect = new Rectangle(width/2, height/2, width, height);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0,param);
        ImageIO.write(bi, type, new File(dest));
    }
    /*
     * 图片裁剪通用接口
     */

    public  boolean cutImage(String src, String dest, int x, int y, int w, int h, String type, Response response) throws IOException{
        InputStream in=null;
        FileImageInputStream inn=null;
        try {
            inn = new FileImageInputStream(new File(src));
//            Iterator iterator = ImageIO.getImageReadersByFormatName(type);
            Iterator<ImageReader> iterator = ImageIO.getImageReaders(inn);
            ImageReader reader = (ImageReader) iterator.next();
            in = new FileInputStream(src);
            ImageInputStream iis = ImageIO.createImageInputStream(in);
            reader.setInput(iis, true);
            ImageReadParam param = reader.getDefaultReadParam();
            Rectangle rect = new Rectangle(x, y, w, h);
            param.setSourceRegion(rect);
            BufferedImage bi = reader.read(0, param);
            if(bi.getHeight()<h||bi.getWidth()<w) {
                response.json("{\"state\" : 500, \"result\" : \"选框超出图片边界了。\"}");
                return false;
            }
            else
                ImageIO.write(bi, type, new File(dest));
            return true;
        }
        finally {
            inn.close();
            in.close();
        }
    }
    /*
     * 图片缩放
     */
    public static void zoomImage(String src,String dest,int w,int h) throws Exception {
        double wr=0,hr=0;
        File srcFile = new File(src);
        File destFile = new File(dest);
        BufferedImage bufImg = ImageIO.read(srcFile);
        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);
        wr=w*1.0/bufImg.getWidth();
        hr=h*1.0 / bufImg.getHeight();
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public void deleteFile(String filePath) {
        File file = new File(filePath);
        try {
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    System.out.println("删除成功！"+filePath);
                }
                else{
                    System.out.println("删除失败！"+filePath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 获取图片类型（实际）
     * @param filePath
     * @return
     */
    public static String getFileExt(String filePath) {
        FileInputStream fis = null;
        String extension = FilenameUtils.getFileExtension(filePath);
        try {
            fis = new FileInputStream(new File(filePath));
            byte[] bs = new byte[1];
            fis.read(bs);
            String type = Integer.toHexString(bs[0]&0xFF);
            if(JPG_HEX.equals(type))
                extension = JPG_EXT;
            if(PNG_HEX.equals(type))
                extension = PNG_EXT;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return extension;
    }
    private static final String JPG_HEX = "ff";
    private static final String PNG_HEX = "89";
    private static final String JPG_EXT = "jpg";
    private static final String PNG_EXT = "png";

}
